0

I have one object:

var callback = {
    onValueChange: function () { },
    onTabPressed: function () { },
    onFocus: function () { }
};

On my page, i have different editors, like textEditor and numericEditor, and i bind them separately:

function bindEditors() {
    var editors = $(".editor");
    editors.each(function (i) {
        var editor = $(this);
        var editorType = editor.attr("data-editorType");

        if (editorType == "textEditor") {
            bindTextEditor(editor);

        } else if (editorType == "numericEditor") {
            bindNumericEditor();
        }
    });
};
function bindTextEditor(editor) {
    editor.bind("change", function () {
        // calculate value
        callback.onValueChange($(this), value);
    });
};
function bindNumericEditor(editor) {
    editor.bind("change", function () {
        // calculate value
        callback.onValueChange($(this), value);
    });
};

My question is:

Is ok to keep callback object outside of the binding functions? Wouldn't each binding function create a copy of the callback object? (which uses extra memory)

Or should i pass the callback object as a parameter to each of the binding functions?

2 Answers 2

1

It doesn't create copies of the enclosed object, just references to the same object, so I wouldn't worry about that. And I definitely wouldn't pass callback as a parameter.

I don't think there's anything crazily wrong with what you wrote, but if you wanted to cut down on your code's complexity, you could just bind it once and do the switch inside the binding itself:

$(".editor").bind("change", function(){
  var editor = $(this);
  var editorType = editor.attr("data-editorType");

  if (editorType == "textEditor") {
    //calculate value
  } else if (editorType == "numericEditor") {
    //calculate value
  }

  callback.onValueChange(editor, value);
});

That probably doesn't perform any differently, but it's cleaner.

Sign up to request clarification or add additional context in comments.

Comments

1

1) Is ok to keep callback object outside of the binding functions?

Absolutely!

2) Wouldn't each binding function create a copy of the callback object?

No.

3) Or should i pass the callback object as a parameter to each of the binding functions? No.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.