2012-05-25 88 views
1

我试图让jPages与EmberJS一起使用。看起来,jPages试图绑定到因Ajax调用而无法及时加载的元素。有没有人得到这个工作?这里的的jsfiddle:http://jsfiddle.net/stevenng/8hDRJ/33/获取jQuery jPages插件以使用EmberJS和Ajax调用

把手

<div class="songs"> 
    <script type="text/x-handlebars"> 
    {{#view Songs.songsView}} 
     <div id="song-items"> 
     {{#each Songs.songsController}} 
      <div class="song"> 
       <p>{{artist}}</p>     
      </div> 
     {{/each}} 
     </div> 
     <div class="pagination"></div> 
    {{/view}} 
    </script> 
</div>​ 

的JavaScript

Songs.songsController = Em.ArrayController.create({ 
    content: [], 
    addSong: function(song) { 
     this.pushObject(song); 
    }, 
    getSongs: function() { 
     var self = this; 
     $.ajax({ 
      url: 'http://test.com/getSongs?callback=?', 
      dataType: "jsonp", 
      success: function(data){ 
       var obj = $.parseJSON(data); 
       for (var i=0; i<obj.songs.length; i++) { 
       self.addSong(Songs.song.create(obj.songs[i]));  
       } 
      } 
     }); 
    } 
}); 

Songs.songsView= Em.View.extend({ 
    didInsertElement: function() { 
     $('.pagination').jPages({ 
     containerID: "song-items", 
     perPage: 2 
     }); 
    } 
}); 

回答

1

正如你所说,这首歌元素还不在DOM当你实例jPages插件。这就是为什么它不起作用。

我的解决方案是在控制器上创建一个属性loaded。当它设置为true,认为知道的内容被加载,它可以实例jPages,看到http://jsfiddle.net/pangratz666/dpqCn/

把手

<script type="text/x-handlebars" data-template-name="song" > 
    {{content.artist}} 
</script>​ 

的JavaScript

Songs.songsController = Em.ArrayController.create({ 
    content: [], 
    getSongs: function() { 
     var self = this; 
     $.ajax({ 
      success: function(data) { 
       var songs = data.songs.forEach(function(song){ 
        return Songs.Song.create(song); 
       }); 

       // add all songs at once 
       self.pushObjects(songs); 

       // set the loaded property to true to indicate that the content is filled 
       self.set('loaded', true); 
      } 
     }); 
    } 
}); 

Songs.SongsView = Ember.ContainerView.extend({ 
    childViews: 'songsView paginationView'.w(), 
    loadedBinding: 'controller.loaded', 

    // invoked when the loaded property of the controller is changed 
    _loadedChanged: function() { 
     if (this.get('loaded')) { 
      // get the songsView instance 
      var songsView = this.get('songsView'); 

      // call jPages plugin on next run loop 
      // when content has been filled and elements have been inserted to DOM 
      Ember.run.next(this, function() { 
       this.$('.holder').jPages({ 
        containerID: songsView.get('elementId') 
       }); 
      }); 
     } 
    }.observes('loaded'), 

    paginationView: Ember.View.create({ 
     classNames: 'holder'.w() 
    }), 

    songsView: Ember.CollectionView.create({ 
     contentBinding: 'parentView.controller.content', 
     tagName: 'ul', 
     itemViewClass: Ember.View.extend({ 
      templateName: 'song' 
     }) 
    }) 
}); 

另一个说明:您的命名约定不符合Ember标准。请参阅Emberist的blog post。所以类是UpperCase,属性和实例是lowerCase