2012-05-25 31 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