"Mastering the art of running a successful Dojo

As I delve into learning dojo, I encountered some peculiar syntax in a project on GitHub.

  dojo.declare('app.services.Favorites', [ dojo.store.Memory ], {

    constructor : function() {
      this.inherited(arguments);

      dojo.subscribe('/favorites/add', dojo.hitch(this, 'put'));
      dojo.subscribe('/favorites/remove', this, function(person) {
        this.remove(person.id);
      });
    },

    put : function() {
      this.inherited(arguments);
      this._save();
    },

    remove : function() {
      this.inherited(arguments);
      this._save();
    },

    _save : function() {
      if (!storage) { return; }
      window.localStorage.setItem('favorites', JSON.stringify(this.data));
    }

  });

  // create an instance that overwrites the constructor
  app.services.Favorites = new app.services.Favorites({
    data : data ? JSON.parse(data) : []
  });

}()

I'm curious about the meaning behind this part. Can someone clarify?

dojo.subscribe('/favorites/add', dojo.hitch(this, 'put'));
          dojo.subscribe('/favorites/remove', this, function(person) {

Answer №1

The Dojo Topic System is utilized here, functioning as a form of global events that are independent of stores.

Any piece of code can publish a "topic," typically in the format of a URL or filesystem path for organization purposes, along with an optional data object or additional arguments in newer versions of Dojo. It is advisable to use the dojo/topic module instead of dojo/connect, especially in later versions like 1.7.

// Dojo 1.7+
require(["dojo/topic"], function(topic){
    topic.publish("some/topic", "one", "two");
});

// Dojo 1.7 (AMD)
require(["dojo/_base/connect"], function(connect){
    connect.publish("foobar", [{
        item:"one", another:"item", anObject:{ deeper:"data" }
    }]);
});

// Dojo < 1.7
dojo.publish("foobar", [{
    item:"one", another:"item", anObject:{ deeper:"data" }
}]);

Other sections of code can subscribe to specific topics by registering callback functions. Once again, it is recommended to utilize dojo/topic over dojo/connect, particularly in newer versions such as 1.7.

// Dojo 1.7+
require(["dojo/topic"], function(topic){
    topic.subscribe("some/topic", function(){
        console.log("received:", arguments);
    });
});

// Dojo 1.7 (AMD)
require(["dojo/_base/connect"], function(connect){
    connect.subscribe("/foo/bar/baz", function(data){
        console.log("i got", data);
    });
});

// Dojo < 1.7
dojo.subscribe("/foo/bar/baz", function(data){
    console.log("i got", data);
});

Subscribers to a published topic will be notified when the event occurs, and their respective callback functions will execute. The data object provided with the publish operation is passed to each callback function if available.

Note that subscriptions created after a publish event will not trigger callbacks for previous events. Subscriptions respond only at the time of the publishing event.

This GitHub project seems to be using an outdated Dojo version due to the presence of dojo.subscribe instead of the modern dojo/topic module. As the latest Dojo release is 1.9, it is recommended to upgrade and utilize the updated functionalities introduced from version 1.7 onwards.

Documentation links for relevant Dojo versions:

  • dojo.publish and dojo.subscribe (applicable for 1.6 and 1.7)
  • dojo/topic module (for 1.9, recommended for 1.7+ coding style)

It is highly encouraged to update to the latest Dojo version and utilize the dojo/topic module with its publish and subscribe methods, avoiding the deprecated dojo.publish and dojo.subscribe approaches.

Example snippets sourced from documentation references.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sharing a unique JSON message on Slack via a webhook

Is there a way to send a custom JSON message with indentation using a Slack webhook in a Node.js app? var Slack = require('slack-node'); var JsonMessage = process.argv[2]; webhookUri = "https://hooks.slack.com/services/XXXX/xxxx/xxxxxxxx"; sla ...

Randomly positioning an image while the page is loading

I've been developing a portfolio website to showcase my design work, but I've encountered a minor issue. My goal is to have the images load in random positions and then make them draggable using Dragabilly. However, sometimes all the images end ...

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

Sit tight as we prepare all static assets for loading on the screen

Currently, I am developing a vuejs application that will incorporate video elements. To enhance user experience, we are interested in preloading these videos upon the initial loading of the web application. I am considering using a listener like, documen ...

I'm looking for the documentation for the latest version of Footable's Events. Can you point me

Does anyone know where to find information on the events that are fired for Footable and how to handle them? I checked the documentation at , but it doesn't provide much detail on events. If you have any resources or suggestions, please let me know! ...

The chaotic world of Android WebKit versions 2.x and 3.x

I have been working on an Android app and my goal is to make it compatible with Android versions 2.2 and above. Currently, due to issues with the WebView control, I am restricted to targeting Android 4.0 and higher. The app primarily uses HTML, CSS, Java ...

I'm receiving a TypeError in Nodejs indicating that the hashPassword function is not recognized as a function. Can anyone offer advice on how to

How's everything going? I could really use your assistance! I'm currently working on developing an API for registering authenticated users, with data storage in the MongoDB Atlas database (cloud). Unfortunately, I've run into a troubling er ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...

Encountered an error with a JSON object in node and express: Unexpected colon token

I'm currently in the process of developing a small web service using Node.js and Express, and I've encountered an issue. It all runs smoothly until I attempt to utilize it with Ajax in a web browser. When I test it in Postman, everything works fi ...

best way to display an array in HTML

When I input a manufacturer, I want to display the complete data from each object inside the array in the HTML. However, when I call the function on the HTML page, all I get back is the word object repeated as many times as the Manufacturer is defined in ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Adding a border in jQuery or Javascript to highlight empty form fields

After making the decision to dive into the world of Javascript, I've been dedicated to perfecting a script that will encase empty elements with a border right before the user submits a form. My ultimate goal is to implement live validation in the form ...

Setting a specific index in an array of objects in React: A comprehensive guide

I currently have a useState() object structured as follows: const [financeSummary, setFinanceSummary] = useState({ discountRate: 10, financeRate: 10, reinvestRate: 10, inflationRate: 3, singleInvestment: new Array( ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

Troubleshooting: Android compatibility issues with dynamic source for HTML 5 video

My HTML5 video with dynamic source loaded using JavaScript is functioning properly in a web browser but encountering issues within an Android PhoneGap build application. Take a look at the code snippet below: JavaScript code: $('#video_player' ...

Navigating from production lines to the angular directive - what's the best route?

Can anyone advise on the proper method to initialize a variable with factory data in Angular? The current approach I'm using doesn't seem right to me. Am I doing it wrong? $scope.result = []; factoryCities.then(function(data){ $scope.result ...

Could the long-term consequences of utilizing '--force' or '--legacy-peer-deps' be detrimental?

I'm currently working on a react-native project and encountering an error while trying to install the native-base library... npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-prote ...

What is the reason behind including a data string filled with a series of numbers accompanied by dashes in this ajax request?

I stumbled upon a website filled with engaging JavaScript games and was intrigued by how it saves high scores. The code snippet in question caught my attention: (new Request({ url: window.location.toString().split("#")[0], data: { ...