我试图弄清楚当从页面中删除元素时如何执行一些js代码:
jQuery('#some-element').remove(); // remove some element from the page
/* need to figure out how to independently detect the above happened */
Run Code Online (Sandbox Code Playgroud)
是否有为此量身定制的活动,例如:
jQuery('#some-element').onremoval( function() {
// do post-mortem stuff here
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
我有三种不同的方法来初始化和呈现视图及其子视图,并且每个方法都有不同的问题.我很想知道是否有更好的方法可以解决所有问题:
在父级的初始化函数中初始化子级.这样,并不是所有东西都会陷入渲染状态,因此渲染时阻塞较少.
initialize : function () {
//parent init stuff
this.child = new Child();
},
render : function () {
this.$el.html(this.template());
this.child.render().appendTo(this.$('.container-placeholder');
}
Run Code Online (Sandbox Code Playgroud)
问题:
最大的问题是第二次在父级上调用render将删除所有的子事件绑定.(这是因为jQuery的$.html()工作原理.)这可以通过调用this.child.delegateEvents().render().appendTo(this.$el);来减轻,但是第一个,也是最常见的情况是,你正在做更多不必要的工作.
通过附加子项,可以强制render函数了解父DOM结构,以便获得所需的顺序.这意味着更改模板可能需要更新视图的渲染功能.
初始化父级的子级initialize(),但不是追加,而是使用setElement().delegateEvents()将子级设置为父级模板中的元素.
initialize : function () {
//parent init stuff
this.child = new Child();
},
render : function () {
this.$el.html(this.template());
this.child.setElement(this.$('.placeholder-element')).delegateEvents().render();
}
Run Code Online (Sandbox Code Playgroud)
问题:
delegateEvents()现在变得必要,这只是在第一个场景中的后续调用中必需的一点点负面.render()而是在父方法中初始化子项.
initialize : function () {
//parent init stuff
},
render : function () {
this.$el.html(this.template()); …Run Code Online (Sandbox Code Playgroud) 使用backbone.js:
我有一个顶级ModelA,包含2个属性和2个嵌套模型,ModelB和ModelC.ModelB和ModelC各有2个属性如下:
ModelA
attributeA1
attributeA2
ModelB
attributeB1
attributeB2
ModelC
attributeC1
attributeC2
Run Code Online (Sandbox Code Playgroud)
ModelA有ViewA,ModelB有ViewB.ViewA的渲染功能在主体上放置一个新的div,而ViewB的渲染创建一个h1.ViewA的初始化调用ViewB的渲染将h1插入到新的div中.这种分离背后的基本原理是h1可能会发生变化,需要独立于ViewA重新渲染.
ViewA
initialise:
//call ViewA's own render function
this.render()
//call ViewB's render function that further modifies the $("#new") div created earlier.
$("#new").append(ViewB.render().el)
//ViewA's own render function
render: //place <div id="new"></div> onto 'body'
ViewB
render: //create a <h1></h1>
funcB1: //can this access it's parent ModelA's attributes and other objects?
Run Code Online (Sandbox Code Playgroud)
Q1:ViewB有一个函数funcB1.这个函数可以访问它的父模型的属性吗?属性如attributeA1,甚至属性C1(可能是兄弟/堂兄)?
Q2:作为对Q1的进一步扩展,funcB1可以访问与ViewA相关的DOM元素吗?(在这个例子中,#new div?)
问题3:一般情况下,如何定义视图和模型之间的关联,如上所述,以便一切正确联系在一起?
我意识到这个问题有些抽象,但任何感谢任何帮助或指导.