2013-07-30 29 views
4

有没有人有一个代码片段(jsfiddle,也许是个例子),将模板,视图和组件的用法放在一个示例中?寻找关于何时以及如何使用以及如何使用其中一个的实际演示。特别是在概念上非常接近的视图和组件。Ember JS:模板,视图和组件

当需要更复杂的事件处理时,指南会提示视图。

特别是,我有兴趣了解更多关于如何使用这些惯用方法的更好的代码重用和更多DRY视图层代码。特别想知道如何创建嵌套视图层次结构以及如何管理事件冒泡。

+0

[视图VS组件在灰烬的可能重复。 JS](http://stackoverflow.com/questions/18593424/views-vs-components-in-ember-js) –

回答

3

我发现99%的时间模板都是你需要的。视图是当你需要与模板交互或者有一个你想要重用的UI事物时。作为示例,我为tree视图创建了一个视图组件,该视图具有一些复杂的用户交互,我需要在应用程序的几个不同位置使用这些交互。 我也使用视图来处理'无限'scrolling与模板中的数据,该模板将浏览器滚动操作绑定到视图中的方法。然后,这触发控制器来获取更多的结果的方法当Web页面滚动至底部:

App.CompoundPathwaysIndexView = Ember.View.extend({ 
    didInsertElement: function() { 
    var view = this; 
    $(window).bind("scroll", function() { 
     view.didScroll(); 
    }); 
    }, 

    willDestroyElement: function() { 
    $(window).unbind("scroll"); 
    }, 

    didScroll: function() { 
    if(this.isScrolledToBottom() && !this.get('controller').get('fetching')) { 
     this.get('controller').set('fetching', true); 
     this.get('controller').send('fetchMore'); 
    } 
    }, 

    isScrolledToBottom: function() { 
    var documentHeight = $(document).height(); 
    var windowHeight = $(window).height(); 
    var top = $(document).scrollTop(); 
    var scrollPercent = (top/(documentHeight-windowHeight)) * 100; 

    return scrollPercent > 99; 
    } 
}); 

的观点其它实例为inject脚本标签的模板它使用didInsertElement方法渲染后(因为将它们添加到句柄模板中显然是不好的做法)。

例如,激活上的文本框引导预输入功能:

模板:

{{input type="text" placeholder="search" value=search action="query" id="search_box" class="search-query span4"}} 

的视图:

App.ApplicationView = Ember.View.extend({ 
    didInsertElement: function() { 
     $('#search_box').typeahead({ 
     source: function (query, process) { 
      $.getJSON(typeaheadUrl, { query: query }, function (data) { 
       return process(data); 
      }) 
     } 
     }); 
    } 
});