Easy JavaScriptMVC Model and Controller Access from the Chrome Dev Tools Console

Posted by & filed under Front-End Development, JavaScript.

JavaScriptMVC has some great convenience functions for accessing Controllers and Models associated with elements. These functions can really speed up development and debugging. Here I’ll show you how to use the Chrome Developer Tools’ $0 token to make these convenience methods even more convenient.

First let’s look at few examples of how to use the JMVC convenience methods:

//get all controllers for an element
$(".someclass").controllers()
 
//get all controllers of type MyController
$(".someclass").controllers(MyController);
 
//get the first controller
$(".someclass").controller();
 
//call the MyWidget.prototype.doSomething function with an argument
$(".someclass").myWidget("doSomething", "HELLO!");
 
//get the model for an element
$(".someclass").model();

Here’s where the $0 token comes into play. The Chrome Developer Tools $0 token is simply a reference to an inspected node (the highlighted element in the “Elements” tab.) If, for example, you wanted to see a map of the custom data- attributes of an element you would do the following:

  1. Right-click on an element and choose “Inspect Element”
  2. Type “Command + [" to switch to the Console tab
  3. Type $0.dataset in the Console tab

After following the steps above, the console will return a DOMStringMap of the data- attributes on the element you inspected. It's pretty obvious how the $0 token simplifies calling the JavaScriptMVC convenience methods on elements (especially in situations where your Model/Controller elements don't have IDs.) When you have a Model/Controller element selected, you can simply replace the class selectors in the examples above with the token as such:

//get all controllers for an element
$($0).controllers()
 
//get all controllers of type MyController
$($0).controllers(MyController);
 
//get the first controller
$($0).controller();
 
//call the MyWidget.prototype.doSomething function with an argument
$($0).myWidget("doSomething", "HELLO!");
 
//get the model for an element
$($0).model();

Inspecting a JavascriptMVC Model in the Console

Assuming you inspected an element with either a Controller or Model associated, you should see something similar to this.

If you want to try this out on a live JavaScriptMVC application, head over to the JMVC sample Todos application, add a few todos and inspect away!

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>