canjs组件tempate dom live binding

时间:2015-01-14 08:56:50

标签: canjs templatebinding canjs-component

我的代码是实现一个像这个例子的分页页面https://github.com/bitovi/canjs/blob/master/component/examples/paginate.html

我发现message.mustache模板中的{#messages} ... {/ messages}未插入到页面中,而messagelist组件插入事件已被触发,因此我无法对{#messages}进行任何绑定事件中的dom,因为它不存在于页面中。

还有其他方法可以解决这个问题吗?

模板:

message_list.mustache:

<app>
<messagelist deferredData='messagesDeferred'></messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>

message.mustache:

{#messages}}
<dl>
<dt>.....</dt>
<dd>....</dd>
</dl>
{/messages}

组件:

can.Component.extend({
  tag: "messagelist",
  template: can.view('/static/web/tpl/mobile/message.mustache'),    // to load message template
  scope: {
    messages: [],
    waiting: true,
    },
  events: {
    init: function () {
      this.update();
    },
    "{scope} deferreddata": "update",
    update: function () {
      var deferred = this.scope.attr('deferreddata'),
        scope = this.scope,
        el = this.element;
      if (can.isDeferred(deferred)) {
        this.scope.attr("waiting", true);
        deferred.then(function (messages) {
          scope.attr('messages').replace(messages);
        });
      } else {
        scope.attr('messages').attr(deferred, true);
      }
    },
    "{messages} change": function () {
      this.scope.attr("waiting", false);
    },
    inserted: function(){
        // can't  operate the dom  in message.mustache template
    }
  }
});

//to load component template
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
  $("#message-list").html(content)
});

1 个答案:

答案 0 :(得分:0)

我已经解决了问题,但不是最好的,也许有人有更好的方法。

  • 我更改了模板,添加了一个名为<messageitem>
  • 的新组件
  • <messageitem>将加载另一个模板:message.mustache
  • 每个<messageitem>会在插入<messagelist>
  • 时触发插入的事件

新组件:

can.Component.extend({
  tag: "messageitem",
  template:can.view('/static/web/tpl/mobile/message.mustache'),
  events: {
    inserted: function(el, ev){
     // Can-click can not satisfy my needs,
     // because i call the third-party module to bind click event
    // this module will be called repeatedly, not the best way
      reloadModules(['accordion']); 
    }
  }
});

// To load message_list.mustache
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
  $("#message-list").html(content)});

静态HTML:

<body>
<div id="message-list">
....
</div>
</body>

message_list.mustache:

<app>
   <messagelist deferredData='messagesDeferred'>
   {{#messages}}
  <messageitem></messageitem>
  {{/messages}}
   </messagelist>
   <next-prev paginate='paginate'></next-prev>
   <page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>

message.mustache:

<dl class="am-accordion-item" >
...
</dl>