如何知道是否元素创造新的主干视图时已经在DOM [英] How to know if element is already in the DOM when creating new Backbone view

查看:110
本文介绍了如何知道是否元素创造新的主干视图时已经在DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的情况:
当页面打开的第一次,它已经由服务器(PHP)prepared DOM。

here's the situation: When page is opened for the first time, it already has prepared DOM by server(php).

如果用户启用JavaScript,然后我想我的网页转换为Web应用程序(或者无论你怎么称呼它)。
只要JavaScript是初始化,从主干获取服务器的集合。
的问题是,一些这些取出物品已经页面上。

If user has javascript turned on, then i want to convert my page to web app(or whatever you call it). As soon as Javascript is initialized, Backbone fetches collection from server. The problem is, that some of these fetched items are already on page.

现在我怎样才能标记那些已经是在DOM项目?
我怎么能扎起来的骨干看法?

Now how can i mark those items which already are in the DOM? And how can i tie them up with the Backbone view?

推荐答案

一Backbone.View挂接到现有的DOM元素很简单:

Hooking up a Backbone.View to an existing DOM element is simple:

//get a referent to the view element
var $el = $("#foo");

//initialize new view
var view = new FooView({el:$el});

该视图现在处理 #foo 元素的事件,和所有其他View善良。你不应该叫 view.render 。如果你这样做,它会重新渲染视图的元素。这意味着你不能定义任何必要的code中的渲染方法。

The view now handles the #foo element's events, and all the other View goodness. You shouldn't call view.render. If you do, it will re-render the view to the element. This means that you can't define any necessary code in the render method.

至于如何找出哪些元素已经在DOM,以及如何找到为每个视图相应的元素 - 这是更复杂一点不知道你的数据和HTML究竟如何看起来像回答。作为一般的建议,可以考虑使用数据 - * 属性匹配的元素

As to how to find out which elements are already in the DOM, and how to find the corresponding element for each view - that's a bit more complicated to answer without knowing exactly how your data and html looks like. As a general advice, consider using data-* attributes to match up the elements.

让我们假设你有一个DOM树:

Let's say you have a DOM tree:

<ul id="list">
  <li data-id="1">...</li>
  <li data-id="2">...</li>
  <li data-id="5">...</li>
</ul>

您可以绑定/渲染模式,像这样的容器:

You could bind/render a model to the container like so:

var view;

//container element
var $list = $("ul#list");

//find item node by "data-id" attribute
var $item = $list.find("li[data-id='" + model.id+ "']");

if($item.length) {
  //element was in the DOM, so bind to it
  view = new View( {el:$item, model:model} );
} else {
  //not in DOM, so create it
  view = new View( {model:model} ).render();
  $list.append(view.el);
}

这篇关于如何知道是否元素创造新的主干视图时已经在DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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