Implement Ajax applications in MVC mode based on Dojo

Source: Internet
Author: User

I want to implement an application in the project to control the synchronization of audio and text returned by the server during client playback. I believe I have seen baidu songs and audios. Audio and text synchronization and drag-and-drop synchronization are supported, one more function is implemented this time, that is, to play one sentence at a time. Of course, I am not trying to play a song ). in brief, I used JSON (javascript object notation) to transmit data in the interaction with the server, and Newtonsoft's. the Net component processes JSON data serialization. You can define the specific JSON format, for example (the simplest ):

{       Media : [{      text : "......",      start : "...",            end : "...."         },  ....]         }

As for the MVC implementation under js, many people may think that "js is just a script", probably because the emergence of Ajax has improved the views of many people on js, in fact, JavaScript can write fully Object-oriented Programs, because js supports several important features of object-oriented languages, it should have been the js scripts we 've seen all the time that have made a bad impression on everyone. js is originally an object-oriented language and we have seen many structured programs written by it ). taking a look at this article, my implementation is also inspired by it. The extension is to reference the event subscription and publishing mechanism of Dojo.

Let's take a look at the specific implementation of the preceding statement function. In terms of model, we first implement a container-type model, parse JSON data, and have an array of current sentence information and all sentence information), set the current sentence method:

ContainerModel:

dojo.lang.declare('ContainerModel',null,{    initializer : function(jsonData)    {        var jsonObj=dojo.json.evalJson(jsonData);        var sentences=new Array();        for(var key in jsonObj.Sentences)        {            var sentenceObj=new SentenceModel(key,jsonObj.Sentences[key]);            sentences.push(sentenceObj);        }        this._sentences=sentences;        this._url=jsonObj.MediaUrl;        this._selectedSentence = sentences[0]    },        getSentences : function () {        return [].concat(this._sentences);    },    addItem : function (sentence) {        this._sentences.push(sentence);    },        setSelected : function (sentence) {        this._selectedSentence = sentence;    },        reset : function (){        this._selectedSentence = this._sentences[0];    }});

ItemModel:

Dojo. lang. declare ('itemmodel', null ,{
Initializer: function (id, sentence)
{
This. _ id = id;
This. _ jsonSentence = sentence;

Dojo. event. topic. subscribe ("/PositionChange", this, this. invokeActive );
},

InvokeActive: function (currentPos ){
// If curPos between this. startTime and this. endTime pulish:
If (this. _ jsonSentence. StartTime <= currentPos & this. _ jsonSentence. EndTime> currentPos)
Dojo. event. topic. publish ("/MeInvoked", this );
},

ClickActive: function (){
Dojo. event. topic. publish ("/MeClicked", this );
}
});

Another model represents the information of the preceding sentence, including text, startTime, and endTime, and is scheduled to be published after the "/positionChange" event ), define two methods at the same time. Here, dojo is used in View. event connect connects it to a specific user event) is used to publish the event that is activated for the current object. In view, the event is subscribed to by the controller to activate the published event, the controller refreshes the current item of the container model during processing and updates the view performance (for example, adding a style). In addition to event connection and subscription for other objects, the view object, the render method render all the items of the container model into a specific html element such as span), which determines the display form of the model:

Viewer-Controller:

/**
* A container view class to render on the webpage
*/
Dojo. lang. declare ('mainview', null ,{
Initializer: function (model, controller, elements ){
This. _ model = model;
This. _ controller = controller;
This. _ elements = elements;

Dojo. event. topic. subscribe ("/MeInvoked", this. _ controller, this. _ controller. proccessInvoke );
Dojo. event. topic. subscribe ("/MeClicked", this. _ controller, this. _ controller. proccessClick );
},

Render: function (){
Var div = this. _ elements. div;
// Remove children
For (var I = 0; I <div. childNodes. length; I ++)
{
Div. removeChild (div. childNodes [I]);
}
Div. innerHTML = "";
Div. innerText = "";

Var items = this. _ model. getSentences ();
For (var key in items ){
Var span = document. createElement ("span ");
Span. id = items [key]. _ id;
Span. appendChild (document. createTextNode (items [key]. _ jsonSentence. Sentence ));
Span. appendChild (document. createElement ("br "));
Div. appendChild (span );

If (key = 0)
Dojo.html. addClass (document. getElementById (this. _ model. _ selectedSentence. _ id), "selected ");

Dojo. event. connect (span, 'onclick', items [key], 'clickactive ');
}
}

});

/**
* A common controller class,
* Execute some utilities operations.
*/
Dojo. lang. declare ('maincontroller', null ,{
Initializer: function (model ){
This. _ model = model;
},

DisplaySentence: function (){
// Actual method
Dojo. event. topic. publish ("/DisplaySentence", this. _ model. _ selectedSentence. _ jsonSentence );
},

ProccessInvoke: function (sentence ){
// Proccess details
This. proccessRightShow (sentence );
},

ProccessClick: function (sentence ){
// Proccess details
This. proccessRightShow (sentence );
// Set player pos (start, end)
SetPlayerPos (sentence. _ jsonSentence. StartTime );
},

ProccessRightShow: function (sentence ){
// Lighten sentence and show sentence on the right

If (this. _ model. _ sentences [0] = sentence | this. _ model. _ selectedSentence! = Sentence)
{
// Change origin selectedSentence's css
Dojo.html. removeClass (document. getElementById (this. _ model. _ selectedSentence. _ id), "selected ");
This. _ model. setSelected (sentence );
// Change new current selectedSentence's css
Dojo.html. addClass (document. getElementById (this. _ model. _ selectedSentence. _ id), "selected ");
Document. getElementById (parseInt (this. _ model. _ selectedSentence. _ id/1.2). scrollIntoView (true );
// Pass sentence to show in right in another func
This. displaySentence ();
}
}
});

The approximate mode is as follows:

In the figure, the object initialization will subscribe an appropriate event for processing when the event is publish. the dotted line indicates that the user clicks to process the event once, and the free line indicates that the text is processed along with the playback, such as the current item is highlighted) this process continues during the playback process. In fact, event publishing does not point to a specific object as shown in the figure (to be easy to understand in the figure). It means who subscribes to and processes the event!

I believe that with this, it is okay to run this model. I am so busy to share it with you. In addition, do not forget the dojo require.

dojo.require('dojo.lang.*');
dojo.require("dojo.event.*");
dojo.require("dojo.event.topic");
dojo.require("dojo.html.*");
dojo.require("dojo.json");
dojo.require("dojo.io.*");

It is still difficult to develop scripts. In terms of development environment or control, as mentioned in Pragmatic Programmer, "imperfect systems, absurd time scales, ridiculous tools, and impossible needs -- in such a world, let us safely drive '"!

  1. Web development under AJAX and XmlHttpRequest
  2. Introduction to the use of Ajax in ASP. Net
  3. Use AJAX extenders to customize controls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.