结合呈现回调Backbone.js的 [英] Binding render callback in Backbone.js

查看:74
本文介绍了结合呈现回调Backbone.js的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Backbone.js的文档:

每当UI操作导致模型的属性变化,
  模型触发改变事件;所有显示视图
  模型的数据通知的事件,导致他们重新渲染。

Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's data are notified of the event, causing them to re-render.

所以我想,render()方法应该绑定到改变事件在默认情况下。而下面的code不工作:

So I suppose that render() method should be bound to "change" event by default. However the following code does not work:

TestModel = Backbone.Model.extend({});
TestView  = Backbone.View.extend({
    render: function() {
        alert('render called');
    }
});
var mod  = new TestModel;
var view = new TestView({model:mod});
mod.change();

它只能如果我添加显式绑定电话:

It works only if I add explicit bind call:

initialize: function() {
    this.model.bind('change', this.render, this);
}

这是否意味着我的默认的理解渲染()回调是不正确的,我们应始终结合手工渲染()回调?

Does this mean that my understanding of default render() callback is not correct and we should always bind render() callback by hand?

推荐答案

除非一些在过去几个月已经改变了,没错,就是这样的。这是一件好事,因为它提供了灵活性,以在视图渲染/重新呈现(例如,某些应用程序可能需要渲染模式已经坚持在服务器上后,才认为,不一定当它改变了浏览器)。如果您想在一个模型属性改变你的观点总是重新渲染,你可以结合它的渲染方法,模型改变事件你自己的基本观点扩展默认骨干视图,然后扩展从所有的具体意见。例如:

Unless something has changed in the last few months, yes, that is the case. This is a good thing, as it gives flexibility as to when views are rendered/re-rendered (for example, some applications might want to render a view only after a model has been persisted on the server, not necessarily when it changes in the browser). If you want your views to always re-render when a model attribute changes, you can extend the default backbone view with your own base view that binds its render method to the model change event, then extend all your concrete views from that. Ex:

MyView = Backbone.View.extend({
    initialize: function() {
        Backbone.View.prototype.initialize.apply(this, arguments);
        this.model.bind('change', this.render);
    }
});

MyConcreteView = MyView.extend({...});
var model = new Backbone.Model({...});
var view = new MyConcreteView({model: model});
model.set({prop: 'value'});

这篇关于结合呈现回调Backbone.js的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆