任何人都可以建议设计模式来分离JavaScript中的业务逻辑和表示逻辑吗? [英] Can anyone suggest design pattern to separate business logic and presentation logic in JavaScript?

查看:109
本文介绍了任何人都可以建议设计模式来分离JavaScript中的业务逻辑和表示逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将开发移动网络应用程序。
App将使用Web服务提供后端数据。
所有演示和业务逻辑都需要用javascript编写。

I am going to develop mobile web application. App will use web services for back-end data. All presentation and business logic needs to write in javascript.

在ios和android中有不同的设计。

There is different design in ios and android.

并且不想为两者分别重写业务逻辑。

And don't want to rewrite business logic separately for both.

任何人都可以建议设计模式将JavaScript中的业务逻辑和表示逻辑分开。

Can anyone suggest design pattern to separate business logic and presentation logic in JavaScript.

推荐答案

一个好的设计模式是设计一个REST-fulAPI,用于存储,检索和修改应用程序运行的数据。然后设计共享此公共API的单独用户界面。编写代码时,使用单独的原型和函数来表示和操作原型中的数据,这些原型用于表示数据在用户界面中的外观或控制方式。

A good design pattern is to design a "REST-ful" API for storing, retrieving, and modifying the data that the application operates on. Then design separate user interfaces that share this common API. When writing the code, use separate prototypes and functions for representing and manipulating the data from the prototypes used to represent the way the data looks or is controlled in the user interface.

您还可以通过使用CSS在iOS和Android上控制应用程序的外观来实现可重用性,同时在两个版本的应用程序中仍使用相同的HTML DOM结构。换句话说,您可以通过操纵DOM元素的class属性而不是显式修改style属性来获得更多的可重用性,依赖于CSS来应用基于类的样式。然后,在大多数情况下,您可以使用相同的JavaScript代码,但只是向不同的用户代理提供不同版本的CSS。可能会出现其他差异;我只是建议在它们出现时将它们重构为自己的函数。

You can also achieve reusability by using CSS to control the appearance of your application on iOS and Android, while still using the same HTML DOM structure in both versions of the application. In other words, you can get more reusability by manipulating the "class" attribute of the DOM elements rather than explicitly modifying the "style" attribute, relying on the CSS to apply the style based on the class. Then, for the most part, you can get away with using the same JavaScript code, but simply providing different versions of the CSS to the different user agents. There may be cases where additional differences show up; I simply suggest refactoring them into their own functions as they show up.

正如其他人所指出的,有许多现有的JavaScript框架(例如Sencha Touch)已经抽象出移动设备的视图逻辑,允许您只编写模型并控制逻辑部分。如果你有UI组件的抽象,那么唯一需要维护的分离是模型和控制器之间的分离。

As others have pointed out, there are a number of existing JavaScript frameworks (such as Sencha Touch) that already abstract the view logic for mobile devices, allowing you to just write the model and control parts of the logic. If you have an abstraction for the UI components, then the only separation that would need to be maintained is the one between the model and the controller.

这篇关于任何人都可以建议设计模式来分离JavaScript中的业务逻辑和表示逻辑吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆