JSPatch 通过 Objective-C 运行时桥接 Objective-C 和 JavaScript。您只需要包含一个小的引擎就可以在 JavaScript 中调用任何 Objective-C 类和方法。这使得 APP 获得了脚本语言的力量:添加模块或用 Objective-C 代码替换来动态修复错误。
JSPatch 正在开发中,欢迎大家一起改进项目。
注意:请访问 Wiki 以获取完整文档。
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[JPEngine startEngine];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
[JPEngine evaluateScript:script];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.window addSubview:[self genView]];
[self.window makeKeyAndVisible];
return YES;
}
- (UIView *)genView
{
return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
}
@end
// demo.js
require('UIView, UIColor, UILabel')
defineClass('AppDelegate', {
// replace the -genView method
genView: function() {
var view = self.ORIGgenView();
view.setBackgroundColor(UIColor.greenColor())
var label = UILabel.alloc().initWithFrame(view.frame());
label.setText("JSPatch");
label.setTextAlignment(1);
view.addSubview(label);
return view;
}
});
您还可以尝试使用 JSPatch Convertor 自动将 Objective-C 代码转换为 JavaScript。
将 JSEngine.m
、JSEngine.h
和 JSPatch.js
从 JSPatch/
复制到您的项目中。
#import "JPEngine.h"
[JPEngine startEngine]
[JPEngine evaluateScript:@""]
执行 JavaScript[JPEngine startEngine];
// exec js directly
[JPEngine evaluateScript:@"\
var alertView = require('UIAlertView').alloc().init();\
alertView.setTitle('Alert');\
alertView.setMessage('AlertView from js'); \
alertView.addButtonWithTitle('OK');\
alertView.show(); \
"];
// exec js file from network
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cnbang.net/test.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[JPEngine evaluateScript:script];
}];
// exec local js file
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"js"];
NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
[JPEngine evaluateScript:script];
//require
require('UIView, UIColor, UISlider, NSIndexPath')
// Invoke class method
var redColor = UIColor.redColor();
// Invoke instance method
var view = UIView.alloc().init();
view.setNeedsLayout();
// set proerty
view.setBackgroundColor(redColor);
// get property
var bgColor = view.backgroundColor();
// multi-params method (use underline to separate)
// OC:NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
var indexPath = NSIndexPath.indexPathForRow_inSection(0, 1);
// method name contains underline (use double undeline to represent)
// OC: [JPObject _privateMethod];
JPObject.__privateMethod()
// use .toJS() to convert NSArray / NSString / NSDictionary to JS type.
var arr = require('NSMutableArray').alloc().init()
arr.addObject("JS")
jsArr = arr.toJS()
console.log(jsArr.push("Patch").join('')) //output: JSPatch
// use hashes to represent struct like CGRect / CGSize / CGPoint / NSRange
var view = UIView.alloc().initWithFrame({x:20, y:20, width:100, height:100});
var x = view.bounds().x;
// wrap function with `block()` when passing block from JS to OC
// OC Method: + (void)request:(void(^)(NSString *content, BOOL success))callback
require('JPObject').request(block("NSString *, BOOL", function(ctn, succ) {
if (succ) log(ctn)
}));
// GCD
dispatch_after(1.0, function(){
// do something
})
dispatch_async_main(function(){
// do something
})
有关更多详细信息,请转到 wiki 页面: 基本用法
您可以重新定义现有的类并覆盖方法。
// OC
@implementation JPTableViewController
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *content = self.dataSource[[indexPath row]]; //may cause out of bound
JPViewController *ctrl = [[JPViewController alloc] initWithContent:content];
[self.navigationController pushViewController:ctrl];
}
- (NSArray *)dataSource
{
return @[@"JSPatch", @"is"];
}
- (void)customMethod
{
NSLog(@"callCustom method")
}
@end
// JS
defineClass("JPTableViewController", {
// instance method definitions
tableView_didSelectRowAtIndexPath: function(tableView, indexPath) {
var row = indexPath.row()
if (self.dataSource().count() > row) { //fix the out of bound bug here
var content = self.dataSource().objectAtIndex(row);
var ctrl = JPViewController.alloc().initWithContent(content);
self.navigationController().pushViewController(ctrl);
}
},
dataSource: function() {
// get the original method by adding prefix 'ORIG'
var data = self.ORIGdataSource().toJS();
return data.push('Good!');
}
}, {})
有关更多详细信息,请转到 wiki 页面: defineClass 的使用
提供了一些扩展以支持自定义结构类型、C 方法和其他功能,在启动引擎后调用 +addExtensions:
来添加扩展
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[JPEngine startEngine];
//add extensions after startEngine
[JPEngine addExtensions:@[@"JPInclude", @"JPCGTransform"]];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
[JPEngine evaluateScript:script];
}
@end
include('test.js') //include function provide by JPInclude.m
var view = require('UIView').alloc().init()
//CGAffineTransform is supported in JPCGTransform.m
view.setTransform({a:1, b:0, c:0, d:1, tx:0, ty:100})
建议在 JS 中动态添加扩展
require('JPEngine').addExtensions(['JPInclude', 'JPCGTransform'])
// `include()` and `CGAffineTransform` is avaliable now.
您可以在项目中创建自己的扩展来支持自定义结构类型和 C 方法,更详细的说明请查看 wiki 页面: 添加新扩展