Ember Js添加在UI上动态渲染的模型

时间:2015-07-16 01:44:53

标签: ember.js

大家好我有一个问题我想在我的模型中添加另一个项目,在UI上动态呈现。

然而,在我添加它之后它仍然在UI上进行渲染。将其添加到模型列表后是否需要调用函数?

以下是一个例子:

http://emberjs.jsbin.com/mugodifiki/edit?html,js,output

单击图像时,可以将预定义的模型添加到数组并在UI上显示

1 个答案:

答案 0 :(得分:1)

这显然是与owlcarousel库集成引起的问题。在这里可以找到动态更改模型和渲染ui的简单示例,简单的emberjs, http://emberjs.jsbin.com/lodetofere/edit?html,js,output (只需点击列表)

此特定问题是由owlcarousel库对DOM进行的修改引起的。因此,为了解决这个问题,需要在更改模型并恢复dom的初始状态后刷新owlcarousel。

实施例,

http://emberjs.jsbin.com/qanocidoye/edit?html,js

当模型通过切换属性并且轮播重新初始化来更改时,模板的内容部分实际上会刷新。

<强> HBS

<script type="text/x-handlebars" data-template-name="components/test-component">
  {{#if refresh}}
  {{partial "owlContent"}}
{{else}}
  {{partial "owlContent"}}
{{/if}}
  </script>
  <script type="text/x-handlebars" data-template-name="_owlContent">
    <div class="owl-carousel owl-theme">
  {{#each titleModels}}
<div class="item">
    <img {{action "owlItemClicked" this on="click" }} {{bind-attr src=img}}>
</div>
{{/each}}
</div>
  </script>

<强> JS

App.TestComponentComponent = Ember.Component.extend({

//     classNames: ['owl-carousel', 'owl-theme'],
    items: 8,
    touchDrag: true,
    mergeFit: false,
    center: true,
    addClassActive: true,
    mouseDrag: true,
    slideSpeed : 1000,
    margin: 2,
  refresh:false,


initCarousel:function(){
  var self = this;
            var options = {};

            options.items = self.get('items');
            options.touchDrag = self.get('touchDrag');
            options.mergeFit = self.get('mergeFit');
            options.center = self.get('center');
            options.addClassActive = self.get('addClassActive');
            options.mouseDrag = self.get('mouseDrag');
            options.slideSpeed = self.get('slideSpeed');
            options.margin = self.get('margin');
            self._options =   options;
            self._owl = self.$(".owl-carousel").owlCarousel(options);
},
    didInsertElement: function(){
            this.initCarousel();
    },
  refreshCarousel:function(){
    var self = this;
   Em.run.next(function(){
      self.initCarousel();
    });
  }.observes('refresh'),


  actions: {
    owlItemClicked: function(titleModel) {
      var self = this;
      var content = "<div class=\"item dodgerBlue\"><h1>test</h1></div>";
         var newModel = Ember.Object.create({ index: 3, img: "http://www.cs.rice.edu/~dwallach/comp314_f99_ga/%257Eavinash/comp314/project3/pretty/pic1s.jpg"});
      console.log(this.get('titleModels'));
      //THIS ADDS IT TO THE MODEL BUT IS NOT RENDERED ON UI
      this.get('titleModels').push(newModel);
      alert('new model has been added');
      console.log(this.get('titleModels'));

      this.toggleProperty("refresh");
    }
  }
});

你可能会想出一个更优雅的解决方案,但这是主要的想法。