将coffee脚本转换为简单的扩展

converting coffee script to simple extend

本文关键字:简单 扩展 转换 coffee 脚本      更新时间:2024-01-18

我有一些咖啡脚本-

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
   });
 };

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不会做任何类似的事情,而且模型和视图无论如何都是非常不同的。