Binding properties to rerender a view?


#1

What’s the Ember best practice way to bind a model to a view so that if the model changes, then the view rerenders?..

I have a canvas element set up as a view:

<div id="canvas_container">
     {{view "App.CanvasView"}}
</div>

To allow a user to change a rectangle’s colour, I loop over the data model to load the fillStyle value

{{#each}}
     <button {{action 'loadFill' fillStyle}}>Change Colour</button>
{{/each}}

Here’s the controller:

App.IndexController = Ember.ArrayController.extend({

    actions:  {
        loadFill: function(fillStyle)    {
            // ** How to bind the fillStyle and so rerender the view? **
        }
    }    
});

Here’s the view:

App.CanvasView = Ember.View.extend({
    tagName: "canvas",
    attributeBindings: ['height', 'width'],
    height: 400,
    width: 600,

    init: function() {
        this._super();
        this.set("controller", App.IndexController.create());
    },

    didInsertElement: function(){
        this.drawItem();
    },

    drawItem: function(){
        var canvas = Ember.get(this, 'element');
        var ctx = canvas.getContext("2d");

        // **** how to bind to controller fillStyle? ****
        ctx.fillStyle = this.get('controller.fillStyle');

        ctx.fillRect(0,0,60,100);
    }
});

Do I need to set up an observer to trigger the rerender?


#2

Yes I added an observer to the view:

widthChanged: function() {
    console.log('rerender');
    this.rerender();
}.observes('controller.testWidth'),

see the fiddle: http://jsfiddle.net/solex16/F9ZaX/5/

Resolved


#3

You don’t need to re-render whenever model changes, it can be done behind the scene :smiley:

{{view Ember.TextField valueBinding=“controllerProperty”}}

More about it here.

http://emberjs.com/api/classes/Ember.Binding.html