当模型更新时,backbone和knockout如何使视图发生变化?
我正在深入研究这两个很棒的作品的源代码,但是,我无法弄清楚它们的实现,模型数据更新视图的那一刻如何立即改变,
一开始,我认为它可能在 Gecko 中使用类似 object.watch()
的东西,显然我在两个来源中都找不到它们
他们的核心思想有什么想法
先谢谢啦~
I'm diving into the source code of these two awesome works,however,I can't figure out the implement of them,how can the moment the data of the model update the view immedately changes,
At the very first beginning,I thought it may use something like object.watch()
in Gecko,and obviously I can't find them in both sources
any ideas of the core thought of them
Thanks in advance~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让我们看一下backbone 事件实现:
调用bind 将传递的函数(回调)存储在散列
_callbacks
中的传递键(ev) 下。解除绑定只是从哈希中删除所有或传递的回调。
触发器将调用存储在传递的密钥下的所有函数。
这是 JavaScript 的优点之一,您可以将函数及其完整范围存储在变量中并稍后调用它们。所以添加结束数据绑定没有魔法。它只是一个数据结构,用于将带有键的函数保存在哈希中并使用该键调用它们。
由于 Backbone 对象 View、Model、Controller 扩展了 Events 对象,因此您可以在所有对象上绑定/触发事件。因此,当视图在模型更改上绑定函数时,模型会在添加、删除等内容时调用
this.trigger('change')
。Lets take a look at backbones Event implementation:
Calling bind you store a passed function (callback) under passed key (ev) in the hash
_callbacks
.Unbind just delete all or the passed callbacks from the hash.
Trigger will call all functions that stored under the passed key.
This is one of the advantages of JavaScript that you can store functions with its full scope in a variable an call them later. So add the end there is no magic in databinding. Its just a data structure to save function with an key in a hash and call them using the key.
As the Backbone object View, Model, Controller extends the Events object, you can bind/trigger events on all of it. So when a view binds a function on model change, the model call
this.trigger('change')
on when ever something was added, removed etc.我不熟悉 Knockout,但 Backbone 在数据更改时手动触发事件。来自
Model#set
:这是来自
Model#change
:视图可以监听
change
事件并相应更新。I'm not familiar with Knockout, but Backbone fires an event manually when data is changed. From
Model#set
:and this is from
Model#change
:Views can listen to the
change
event and update accordingly.Backbone.JS
你的视图需要监听它的模型,并触发模型的更改事件。
我为您创建了一个 jsFiddle 来看看它是如何工作的: http://jsfiddle.net/Atinux/Jb2rd/
我不太了解 Knockout JS,但我不认为这是一样的,如果我找到答案,我会更新我的帖子。
Backbone.JS
Your view need to listen its model, and trigger the model's change event.
I created for you a jsFiddle to see how It works : http://jsfiddle.net/Atinux/Jb2rd/
I don't really know Knockout JS but I don't think that's the same way, I'll update my post if I find the answer.