0

I need your help. How can I use variables in namespaces? Something like this:

$.MyScript = {
    script: $("script")
  , dataID: script.data("id")
  , dataColor: script.data("color")
  , Alerting: function alerting(){
        alert(dataColor);
    }
}
$.Myscript.Alerting;

3 Answers 3

1

You can't access script property before object is created. You can make use of this pattern instead:

$.MyScript = (function() {

    var $script = $("script");

    return {
        script: $script,
        dataID: $script.data("id"),
        dataColor: $script.data("color"),
        alerting: function alerting() {
            alert(this.dataColor);
        }
    }
})();

$.MyScript.alerting();
Sign up to request clarification or add additional context in comments.

1 Comment

@JohnSmit Mark your question as solved by accepting this answer as a solution to your question. Just click on the tick on the top left side of this answer (below the votes).
1

First of all, that's not the right way to write a jQuery plugin, if that's what you are trying to do. Consult with jQuery's Plugins/Authoring docs to learn the right way.


Apart from that, the way you have the code now you can access the dataColor by referencing the parent object with the keyword this.

I am removing the code from my answer, because you have other issues as well. Look @dfsq's answer for the solution to your issue.

I am just leaving my answer here as a reference to the official docs.

Comments

1

I suggest you a more general approach, without involving jQuery. You can always create your own namespace, and extend it.

Read this beautiful article by Addy Osmani for further details.

/* define a global var, the root of your namespace */
var myNamespace = myNamespace || {};

/*
 * init and populate your ns inside a immediately invoked function expression
 * you can pass the jQuery object as argument if you need it in your business logic
 * but it is not necessary
 */
(function(ns, $){
    ns.ScriptObject = function($script){
      var $s = $script;

      this.getDataColor = function(){
         return $s.data("color");
      }

      this.getDataId = function(){
         return $s.data("id");
      }

      /* add further methods */
    }


})(myNamespace ,jQuery)

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.