0

私はこのようなものを持っています

var obj = new someClass(el, {
    onOne: function () {
        doThis();
    },
    onTwo: function () {
        doThis();
    },
    onThree: function () {
        doThis();
    },
    onFour: function () {
        doThat();
    }
});

したがって、最初の3つのイベントの結果は同じになり、4番目のイベントのみが異なります。このように繰り返しのように見えるので、こういうことができるといいなと思っていました

var obj = new someClass(el, {
    onOne: 
    onTwo: 
    onThree: function () {
        doThis();
    },
    onFour: function () {
        doThat();
    }
});

しかし、私はできません。(クラス自体を変更せずに)似たようなことができる
方法があるのではないかと思います。それはコードをより明確にし、より保守しやすくするだろうと思います。

4

2 に答える 2

3

関数を事前に定義するのはどうですか?

var myHandler = function() {
    doThis();
};

var obj = new Class(el, {
    onOne: myHandler,
    onTwo: myHandler,
    onThree: myHandler,
    onFour: function () {
        doThat();
    }
});

オブジェクトのキーがわかっている場合はfor、たとえばループを追加して試すことができます。

var passIt = { 
    onFour: function() { 
        doThat(); 
    } 
};

var keys = ['onOne', 'onTwo', 'onThree'];
var l = keys.length;
for (var i = 0; i < l; i++) {
    passIt[keys[i]] = myHandler;
}

var obj = new Class(el, passIt);
于 2012-05-21T10:14:38.627 に答える
0

Functions are first-class citizens in the JavaScript world. Unless you've omitted extra processing in your anonymous functions, the following should work:

var obj = new Class(el, { 
    onOne   : doThis
  , onTwo   : doThis
  , onThree : doThis
  , onFour  : doThat
})

Which creates three method aliases for doThis on obj, named onOne, onTwo, and onThree, and a method alias for doThat on obj named onFour.

When you invoke obj.onOne(...), it's equivalent to doThis.call(obj, ...).

Note: I'm not sure you're using MooTool's Class() constructor properly in your example. Reading the docs, it looks like Class excepts only one argument, a properties object (or function) that the newly created object will inherit from. If the code doesn't work, try removing el and adding an 'Extends' : el property to the object literal. I've never used MooTools personally, though, so I'm not sure what to expect.

于 2012-05-21T12:57:02.953 に答える