将咖啡脚本转换为javascript - 简单扩展

时间:2013-12-02 17:23:39

标签: javascript inheritance coffeescript

我有一些咖啡脚本 -

class Zoo.CollectionView extends Zoo.View

  _set_element_attributes: ->
    @$el.data(view: this)
    @$el.addClass('collection')
    return unless @collection?
    @$el.attr('data-name': @collection.collection_name)
    @$el.attr('data-variant': @variant) if @variant?
    @$el.data(collection: @collection, view: this)

我想转换为javascript并尽可能保持简单。我认为这会奏效,但似乎不喜欢我的延伸。

 Zoo.CollectionView = function() {

 }

 $.extend(Zoo.CollectionView.prototype, Zoo.View.prototype);

 Zoo.CollectionView.prototype._set_element_attributes = function() {
   this.$el.data({
     view: this
   });
   this.$el.addClass('collection');
   if (this.collection == null) {
     return;
   }
   this.$el.attr({
     'data-name': this.collection.collection_name
   });
   if (this.variant != null) {
     this.$el.attr({
       'data-variant': this.variant
     });
   }
   return this.$el.data({
     collection: this.collection,
     view: this
   });
 };

1 个答案:

答案 0 :(得分:0)

CoffeeScript的extends与Backbone的extend兼容,因此您应该可以这样做:

Zoo.CollectionView = Zoo.View.extend({
    _set_element_attributes: function() {
        // This part should be easy and it looks like you
        // have it in hand.
    }
});

我不明白你为什么试图将Backbone.Model的原型合并到Zoo.CollectionView中:

$.extend(Zoo.CollectionView.prototype, Backbone.Model.prototype);

因为你的CoffeeScript没有做那样的事情,模特和视图无论如何都是截然不同的事情。