JS框架如何将模型绑定到视图

How do JS frameworks bind model to a view?

本文关键字:绑定 视图 模型 框架 JS      更新时间:2023-09-26

我最近一直在研究可怕的东西.. :)可怕的东西是流行js frameworks的来源,如backbone.jsangular.jsvue.js等。

我将以Backbone为例。我试图弄清楚模型是如何附加到视图的?

这是代码,如果有人能指出发生这种情况的部分,那就太棒了!https://github.com/jashkenas/backbone/blob/master/backbone.js

实际上,我不明白的部分是任何地方都没有调用innerHTML,那么元素是如何用数据填充的呢?

Backbone 不是 Angular,它不会为你绑定模型到 html,它实际上也不会为你渲染视图,你必须在你的视图中实现渲染方法,并在你认为合适的时候调用它们。事实上,我认为来自 2 路绑定框架的开发人员可能会感到困惑。Backbone就是将所有控制权交给开发人员,但您必须自己完成所有工作。

最小模型 =>视图流示例是这样的

var MyModel = Backbone.Model.extend({
  defaults: {
    test: 'test',
  },
  initialize: function (options) {
    console.log(this.get('test'));
  },
});
var MyView = Backbone.View.extend({
  el: '#your-el',
  initialize: function (options) {
    this.template = _.template('<div><%= test %></div>');        
    this.listenTo(this.model, 'change', this.render);
  },
  render: function () {
    // rendering happens here, innerHTML, $.html(), whichever you prefer
    // and you can pass model data as this.model.toJSON()
    // or you can pass an object with data
    // also, you probably will need a templating library or use 
    // bundled underscore _.template(html, data) method to render blocks of html
    // for example, with underscore 
    this.$el.html(this.template(this.model.toJSON()));
    return this; // for chaining
  },
});
var myModel = new MyModel();
var myView = new MyView({
  model: myModel,
});
myModel.set('test', 'newValue'); // view should render after this call

在 backbonejs.org 查看内置事件列表。