intercellular / cell

A self-driving web app framework
https://www.celljs.org
MIT License
1.51k stars 94 forks source link

Assigning $text from component won't update DOM. #159

Closed joannesalfa closed 6 years ago

joannesalfa commented 6 years ago

I'm currently learning how to use cell.js, I had a doubt how to call external functions inside of components, I discovered an issue that won't assign the variable as $text in first $component from second $component, in the console $text outputs '2' instead of 'counter' but in DOM, it's still 'counter'.

Here is my snippet:

module1= {
  $cell: true,
  $type: 'div',
  _index: 0,
  _items: ["Coffee", "Tea", "Sparkling Water", "Soft Drink"],
  $components: [{
    $type: 'p',
    $text: 'counter'
},{
    $type: "button",
    $text: "Click me",
    onclick: function(){
        module1.$components[0].$text = this._index;
        if(this._index > this._items.length){
            this._index = 1;
        }
        else{
            this._index++;
            this.$text = this._items[this._index];
        }
        // this.$text = this._items.length;
    }
}],
}

Also, `$text:counter: ${this._index} won't work.

gliechtenstein commented 6 years ago

Cell doesn't mutate the original variable you declare (in this case module1), so module1.$components[0] is literally:

{
  $type: 'p',
  $text: 'counter'
}

It's NOT the generated cell node. When you modify module1.$components[0].$text you're simply modifying the original global variable, not the generated cell node.

You should instead select the node itself using DOM traversal method (or using a querySelector method). Here's an example: https://jsfiddle.net/o19chucm/

joannesalfa commented 6 years ago

@gliechtenstein Thanks for your explanation, it clears up my doubt, anyway isn't there a better way to do instead of 'this.parentNode.$components[0]._refresh(this._index);' as easy short cut to call external cell node?

gliechtenstein commented 6 years ago

@joannesalfa cell.js intentionally doesn't introduce any framework-specific APIs because the whole point is to let you interact with the DOM using the native web api.

Another way to do this would be if you set an id or class on the p node and use querySelector to select the node and call the function.

I do think it would be nice to come up with a simpler way to do this while NOT inventing a framework-specific API, still thinking about it. If you have ideas please feel free to make suggestions.

joannesalfa commented 6 years ago

@gliechtenstein Gotcha, it's nice to have simple things. Anyway I don't have ideas to make suggestions, maybe it would be $debug but it might be an API... you can close this issue, have a nice day.