Skip to content

Instantly share code, notes, and snippets.

@ericf
Created June 7, 2012 14:52
Show Gist options
  • Select an option

  • Save ericf/2889217 to your computer and use it in GitHub Desktop.

Select an option

Save ericf/2889217 to your computer and use it in GitHub Desktop.
YUI().use('model', 'view', function (Y) {
Y.FooView = Y.Base.create('fooView', Y.View, [], {
initializer: function () {
var model = this.get('model');
// If this view was constructed with a `model` make its events
// bubble up.
model && model.addTarget(this);
// Listen for this view's `model` to be switched with a new `model`.
this.after('modelChange', this._afterModelChange);
// Listen for this view's current `model` to have its `bar`
// attribute changed. This decouples the responding to the event
// from the publisher of the event. Therefore this event
// subscription still works even if this view's `model` changes.
this.after('model:barChange', this._reRenderBar, this);
},
_afterModelChange: function (e) {
// Remove old `model` as a bubble target, and make the new `model` a
// bubble target of this view. This is what makes this view not care
// which `model` fires its `barChange` event.
e.prevVal && e.prevVal.removeTarget(this);
e.newVal && e.newVal.addTarget(this);
console.log('View\'s `model` changed.');
},
_reRenderBar: function (e) {
// Reflect the `bar` attribute's state change in the DOM.
console.log('Model\'s `bar` attribute changed.');
}
});
var model1 = new Y.Model(),
model2 = new Y.Model(),
view = new Y.FooView({model: model1});
model1.set('bar', 'bla'); // => Model's `bar` attribute changed.
model2.set('bar', 'bla');
view.set('model', model2); // => View's `model` changed.
// `model1` has been "detached" from the `view`, therefore its events no
// longer bubble to the `view`.
model1.set('bar', 'bla bla');
// Now that `model2` is attached to the `view`, its `barChange` event
// bubbles to the `view`.
model2.set('bar', 'bla bla'); // => Model's `bar` attribute changed.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment